<?php

namespace App\ApiBackend\Admin;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

/**
 *  管理员添加更新
 */
class AddUpdate extends ApiBaseController
{
  protected function check(): void
  {
    $ruleArr = [
      'username' => 'required',
      'name' => 'required',
      'deptId' => 'required',
      'roleId' => 'required',
    ];
    //验证
    $validator = Validator::make(request()->all(), $ruleArr, [
      'required' => ':attribute必须填写',
      'min' => ':attribute必须填写',
    ], [
      'username' => '账号',
      'name' => '姓名',
    ]);
    //验证失败
    $errorMsg = "";
    if ($validator->stopOnFirstFailure()->fails()) {
      $errorMsg = $validator->errors()->first();
    }
    if ($errorMsg) {
      $this->result["code"] = 1;
      $this->result["message"] = $errorMsg;
    }
  }

  protected function service(): void
  {
    $isUpdate = $adminId = request('adminId');
    //数据
    $insertData = [
      "username" => request('username'),
      "name" => request('name'),
      "adminDepartmentId" => request('deptId'),
      "adminRoleId" => request('roleId'),
      "remark" => request('remark', ''),
      "phone" => request('phone', ''),
    ];
    //更新数据
    try {
      if ($isUpdate) {//更新
        $insertData['updateTime'] = date('Y-m-d H:i:s');
        DB::table('admin')->where('adminId', $adminId)->update($insertData);
        $this->result["message"] = "更新账户成功";

      } else {//新增
        $insertData['password'] = Hash::make(\request('password'));
        $insertData['createTime'] = date('Y-m-d H:i:s');
        $insertData['status'] = 1;
        DB::table('admin')->insert($insertData);
        $this->result["message"] = "新增账户成功";
      }
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = "失败: " . $exception->getMessage();
    }
  }
}
